package com.atguigu.yygh.hosp.service.impl;


import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.hosp.repository.HospItalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {


    // 自动装配mongo的实现类
    private final HospItalRepository hospItalRepository;

    @Autowired
    public HospitalServiceImpl(HospItalRepository hospItalRepository) {
        this.hospItalRepository = hospItalRepository;
    }

    /**
     * 上传医院接口的方法
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        // 将map转为hospital对象
        String mapString = JSON.toJSONString(paramMap);
        // 再将字符串变为一个对象
        Hospital hospital = JSON.parseObject(mapString, Hospital.class);

        // 将数据加入mongo里面去

        // 判断是否存在相同数据(医院编号)
        String hoscode = hospital.getHoscode();
        // 看是否存在  调用方法去查询
        Hospital hospitalExist = hospItalRepository.getHospitalByHoscode(hoscode);

        // 如果存在就修改
        if (hospitalExist != null) {
            // 表示存在 直接修改
            // 注意修改的话一定要设置id的值不然会重复的
            hospital.setId(hospitalExist.getId());
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
        } else {
            // 表示添加 直接添加
            // 设置id值才能实现

            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
        }
        hospital.setUpdateTime(new Date());
        hospital.setIsDeleted(0);
        hospItalRepository.save(hospital);
    }

    /**
     * 根据医院编号查询医院信息
     *
     * @param hoscode
     * @return
     */
    @Override
    public Hospital getHospitalByHoscode(String hoscode) {
        return hospItalRepository.getHospitalByHoscode(hoscode);
    }
}
